/**
 * Created with JetBrains PhpStorm.
 * User: cgp
 * Date: 13-8-7
 * Time: 下午3:09
 */
var active = -1,
    length = areaInitArray.length,
    focusdElem;
$(document).ready(function(){
    $(document).on('mouseup',function(e){
        var container = $("#mainAreas");
        if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            container.hide();
        }
    });
    $("input.s_p").on('keyup click',function(){
        focusdElem = $(this);
        var t = $(this).val(),
            pos = $(this).offset(),
            top = pos.top+$(this).outerHeight(),
            width = $(this).outerWidth(),
            left = pos.left,
            len = 0,
            newArr = [];
        $("#mainAreas").css({'top':top,'left':left,'width':width});
        if(t) {
            if(!isCN(t)) {
                t = t.toUpperCase();
            }
            for(var j=0;j<length;j++){
                if(areaInitArray[j][0].indexOf(t)==0 || areaInitArray[j][1].indexOf(t)==0) {
                    newArr.push(areaInitArray[j]);
                }
            }
        } else {
            newArr = areaInitArray;
        }
        var i= 0, list = '<div> 请按↑↓或者鼠标点击选择</div>';
        len=newArr.length;
        if(!len) return;
        for(;i<len;i+=1) {
            list += '<li class="item-list" data-title="'+ newArr[i][0]+'">' + newArr[i][0] + '('+newArr[i][1] +')' + '</li>';
        }
        $("#mainAreas").html(list).show().addClass('open');
    });
    $("#mainAreas").on('click','li',function(){
        var txt = $(this).attr('data-title');
        focusdElem.val(txt);
        $(this).parent().hide().removeClass('open');
    });
    $("input.s_p").on('keyup', function(event){
        if(!$("#mainAreas").hasClass('open')) return;
        var key = event.keyCode;
        switch(key){
            case 38:
                moveSelect(-1);
                break;
            case 40:
                moveSelect(1);
                break;
            case 13:
                selectCurrent();
                break;
            default :
                active = -1;
                break;
        }
    });
});
function moveSelect(step) {
    var results =  $("#mainAreas");
    var lis = $("li", results);
    if (!lis) return;
    active += step;
    if (active < 0) {
        active = 0;
    } else if (active >= lis.size()) {
        active = lis.size() - 1;
    }
    lis.removeClass("ac_over");
    $(lis[active]).addClass("ac_over");

};
function selectCurrent() {
    var lis = $("li", $("#mainAreas")),
        text = lis.text();
    $(lis[active]).trigger('click')

};

function isCN(str)
{
    var i=0
    for(;i<str.length;i++)
    {
        if(str.charCodeAt(i)<123) break;
    }

    return i==str.length;
}
